package com.example.shopp_2301.utils

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 解决数据倒灌
 */
class SingleLiveData<T>:MutableLiveData<T> (){
    //定义一个变量，用来监听数据是否发生了变化
    private var flag = AtomicBoolean(false)//防止多线程时数据出现不同的情况(原子性)

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner){
            if(flag.compareAndSet(true,false)){
                //执行下方操作 并将值改为newValue
                observer.onChanged(it)
            }
        }
    }

    //值发生了变化
    override fun setValue(value: T) {
        flag.set(true)
        super.setValue(value)
    }


}